package com.zjh.admin.index.controller;

import com.alibaba.fastjson.JSON;
import com.zjh.admin.sys.model.ResourceEntity;
import com.zjh.admin.sys.model.UserEntity;
import com.zjh.admin.sys.service.ResourceService;
import com.zjh.admin.sys.service.UserService;
import com.zjh.common.constants.Common;
import com.zjh.common.result.Result;
import com.zjh.common.util.EmailHelper;
import com.zjh.common.util.TreeUtil;
import com.zjh.core.exception.SystemException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Random;

/**
 * @author ZHX
 * @Description: 首页controller(登陆登出...)
 * @date 2018/10/03 15:53
 */
@Controller
@RequestMapping(value = "/")
public class IndexController {

    @Autowired
    private UserService userService;


    @Autowired
    private ResourceService resourceService;

    /**
     * 登录视图
     *
     * @param request HttpServletRequest对象
     * @return 视图信息
     */
    @GetMapping(value = "login.html", produces = "text/html;charset=utf-8")
    public String login(HttpServletRequest request) {
        try {
            request.removeAttribute("error");
            return Common.BACKGROUND_PATH + "/login";
        } catch (Exception e) {
            throw new SystemException(e);
        }
    }

    /**
     * 用户登陆
     */
    @PostMapping(value = "signin.html", produces = "text/html;charset=utf-8")
    public String userLongin(UserEntity userEntity, Boolean remeberMe, Model model, HttpServletRequest request) {
        try {
            UserEntity user = userService.findByName(userEntity.getAccountName());
            if (user == null) {
                request.setAttribute("error", "账号不存在");
                request.setAttribute("accountName", userEntity.getAccountName());
                request.setAttribute("password", userEntity.getPassword());
                return Common.BACKGROUND_PATH + "/login";
            } else if (!StringUtils.equals(user.getPassword(), userEntity.getPassword())) {
                request.setAttribute("error", "账号或密码错误");
                request.setAttribute("accountName", userEntity.getAccountName());
                request.setAttribute("password", userEntity.getPassword());
                return Common.BACKGROUND_PATH + "/login";
            } else {
                List<ResourceEntity> list = resourceService.findResourcesMenuByUserId(user.getId().intValue());
                List<ResourceEntity> treeList = TreeUtil.getChildResourceEntitys(list, null);
                model.addAttribute("list", treeList);
                model.addAttribute("menu", JSON.toJSONString(treeList));
                // 登陆的信息回传页面
                model.addAttribute("userEntity", user);
                HttpSession session = request.getSession(true);
                session.setAttribute("userSession", user);
                return Common.BACKGROUND_PATH + "/index";
            }
        } catch (Exception e) {
            throw new SystemException(e);
        }
    }


    /**
     * 用户注册
     *
     * @param userEntity 用户对象
     * @return 视图信息
     */
    @PostMapping(value = "register.html", produces = "text/html;charset=utf-8")
    public String register(UserEntity userEntity) {
        try {
            return Common.BACKGROUND_PATH + "/login";
        } catch (Exception e) {
            throw new SystemException(e);
        }

    }

    /**
     * 欢迎页面
     *
     * @param request HttpServletRequest对象
     * @return 视图信息
     */
    @GetMapping(value = "welcome.html", produces = "text/html;charset=utf-8")
    public String welcome(HttpServletRequest request) {
        try {
            return Common.BACKGROUND_PATH + "/welcome";
        } catch (Exception e) {
            throw new SystemException(e);
        }
    }

    /**
     * 用户退出
     *
     * @return 视图信息
     */
    @GetMapping(value = "logout.html")
    public String logout(HttpServletRequest request) {
        //这里执行退出系统之前需要清理数据的操作
        // 注销登录
        return Common.BACKGROUND_PATH + "/login";
    }


    @RequestMapping(value = "resetPassword.html")
    @ResponseBody
    public Object resetPassword(HttpServletRequest request, String uAccountName) {
        Result result = new Result();
        Random random = new Random();
        StringBuilder str = new StringBuilder();
        for (int i = 0; i<4; i++){
            str.append(random.nextInt(10));
        }
        if (!StringUtils.isEmpty(str.toString())) {
            EmailHelper.sendEmail(uAccountName, "验证码", str.toString());
            result.setData(str.toString());
            result.success();
        } else
            result.error();
        return result;
    }
}
